package com.intelligentmeterreadingsys.otherequipment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.otherequipment.activity.EquipementAddActivity;
import com.intelligentmeterreadingsys.otherequipment.activity.EquipementQueryActivityGroup;
import com.intelligentmeterreadingsys.otherequipment.activity.EquipementRfidCheckActivity;
import com.intelligentmeterreadingsys.otherequipment.activity.EquipementUploadMainActivity;
import com.intelligentmeterreadingsys.otherequipment.db.EquipementDao;
import com.intelligentmeterreadingsys.util.FileNameUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
 * 其它设备管理主界面
 * @author king
 *
 */
public class OtherequipmentMainActivity extends Activity implements OnClickListener{
	private final static int DIALOG=1;
	    public Button button1;//添加
	    public Button button2;//查询
	    public Button button3;//上传
	    public Button button4;//下载
	    public Button button5;//巡检
	    public SharedPreferenceUtil sp=null;
	    public int watertotal=0;
	    public EquipementDao dao=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.otherequipmentmain);
		sp=new SharedPreferenceUtil(this);
		button1=(Button)findViewById(R.id.otherequipment_add);
		button2=(Button)findViewById(R.id.otherequipment_query);
		button3=(Button)findViewById(R.id.otherequipment_upload);
		button4=(Button)findViewById(R.id.otherequipment_download);
		button5=(Button)findViewById(R.id.otherequipment_check);
		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
		button4.setOnClickListener(this);
		button5.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		Intent intent=null;
		switch (v.getId()) {
		case R.id.otherequipment_add:
			intent=new Intent(OtherequipmentMainActivity.this, EquipementAddActivity.class);
			startActivity(intent);
			break;
		case R.id.otherequipment_query:
			intent=new Intent(OtherequipmentMainActivity.this, EquipementRfidCheckActivity.class);
			startActivity(intent);
			break;
		case R.id.otherequipment_upload:
			intent=new Intent(this, EquipementUploadMainActivity.class);
			startActivity(intent);
			break;
		case R.id.otherequipment_download:
			dao=new EquipementDao(this);
			if(dao.queryNoUploadTotal("巡检")>0||dao.queryNoUploadTotal("修改")>0||
					dao.queryNoUploadTotal("更换")>0){
				dao.close();
				Toast.makeText(OtherequipmentMainActivity.this, "还有没上传的数据，不能下载", Toast.LENGTH_SHORT).show();
				return;
			}
			showDialog(DIALOG);
			break;
		case R.id.otherequipment_check:
			intent=new Intent(OtherequipmentMainActivity.this, EquipementQueryActivityGroup.class);
			startActivity(intent);
			break;
		default:
			break;
		}
		
	}
	
	public class download extends AsyncTask<String, Integer, String>{
		
		public HttpClientServer server;
		
		public ProgressDialog dialog;
		
		public download(ProgressDialog dialog){
			this.dialog=dialog;
		}
		

		@Override
		protected String doInBackground(String... params) {
             
			  String userid=sp.getValue(XmlNameHelper.IMSI);
			 
			  Map<String, String> map=new HashMap<String, String>();
			  map.put("imsi", userid);
			   String response=  server.doPost(map, params[0]);
			   System.out.println(response);
			   if(!response.equals("error")){
				   try {
					JSONObject js=new JSONObject(response);
					JSONArray equipement=js.getJSONArray("ovs");
					List<ContentValues> equipementlist=new ArrayList<ContentValues>();
					int a=watertotal=equipement.length();
					if(equipement!=null&&equipement.length()>0){
						
						for(int i=0;i<equipement.length();i++){
							JSONObject jb=equipement.getJSONObject(i);
							ContentValues values=new ContentValues();
							values.put("ep_number",jb.getString("number"));
							values.put("ep_type", jb.getString("typeId"));
							values.put("ep_typename", jb.getString("typeName"));
							values.put("ep_date", jb.getString("date"));
							values.put("lastcheckresult", jb.getString("status"));
							values.put("ep_adds", jb.getString("addr"));
							values.put("ep_locationadds", jb.getString("xxAddr"));
							String jindu=jb.getString("jingdu");
							if(jindu.equals("null")){
								values.put("longitude", 0.0);
							}else{
								values.put("longitude", jb.getDouble("jingdu"));
							}
							String weidu=jb.getString("weidu");
							if(weidu.equals("null")){
								values.put("latitude", 0.0);
								
							}else{
								values.put("latitude", jb.getDouble("weidu"));
							}
							values.put("RFIDnumber", jb.getString("rfid"));
							values.put("lastcheckdate", jb.getString("xjDate"));
							equipementlist.add(values);
							publishProgress(i+1);
						}
						
					}
					
					JSONArray typejson=js.getJSONArray("types");
					
					List<ContentValues> typelist=new ArrayList<ContentValues>();
					if(typejson!=null&&typejson.length()>0){
						for(int i=0;i<typelist.size();i++){
							JSONObject jb=typejson.getJSONObject(i);
							ContentValues values=new ContentValues();
							values.put("number", jb.getString("number"));
							values.put("name", jb.getString("name"));
							typelist.add(values);
						}
					}
				} catch (JSONException e) {
					
					e.printStackTrace();
				}
			   }
			return "error";
			  
		  
		}

		@Override
		protected void onPreExecute() {
			server=new HttpClientServer(OtherequipmentMainActivity.this);
			dao=new EquipementDao(OtherequipmentMainActivity.this);
			
			dialog.setMax(100);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setTitle("下载数据中.......");
			dialog.setCancelable(false);
			dialog.show();
			
		}

	

		@Override
		protected void onProgressUpdate(Integer... values) {
			
			dialog.setProgress((watertotal)/100*values[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			dao.close();
			dialog.cancel();
			System.out.println("result:"+result);
			if(TextUtils.isEmpty(result)){
				Toast.makeText(OtherequipmentMainActivity.this, "下载失败", Toast.LENGTH_LONG).show();
			}else if(result.equals("error")){
				Toast.makeText(OtherequipmentMainActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
			}
			else{
				Toast.makeText(OtherequipmentMainActivity.this, "下载成功,共下载抄表数据:"+watertotal, Toast.LENGTH_LONG).show();
			}
			
			
		}
		
		
	}
	
    @Override
	  	protected Dialog onCreateDialog(int id) {
	  		 Dialog dialog=null;
	  	        switch (id) {
	  	        case DIALOG:
	  	            Builder builder=new android.app.AlertDialog.Builder(this);
	  	            //设置对话框的图标
	  	            builder.setIcon(R.drawable.buttondraw);
	  	            //设置对话框的标题
	  	            builder.setMessage("你有标注的二次抄表哟！确定将下载新的表册！");
	  	             
	  	            
	  	            //添加一个确定按钮
	  	            builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener(){
	  	                public void onClick(DialogInterface dialog, int which) {
	  	                	dao=new EquipementDao(OtherequipmentMainActivity.this);
	  	                	//dao.delectAll(status);
	  	                	dao.close();
	  	                	FileNameUtil fi=new FileNameUtil(OtherequipmentMainActivity.this);
	  	                	fi.delectFile("waterimage");
	  	                	 ProgressDialog pd=new ProgressDialog(OtherequipmentMainActivity.this);
	  	         		  
	  	       			download d=new download(pd);
	  	       			d.execute(RequestUrl.DownloadWaterList);
	  	                }
	  	            });

                    builder.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {
 					
 					@Override
 					public void onClick(DialogInterface dialog, int which) {
 						
 						
 					}
 				});
	  	            //创建一个单选按钮对话框
	  	            dialog=builder.create();
	  	            break;
	  	        case DIALOG+1:
	  	        	 Builder builder1=new android.app.AlertDialog.Builder(this);
	              //设置对话框的图标
	                     builder1.setIcon(R.drawable.buttondraw);
	                     builder1.setMessage("确定下载新巡检数据？");
	                     builder1.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
	  					
	  					@Override
	  					public void onClick(DialogInterface dialog, int which) {						 

                            dao=new EquipementDao(OtherequipmentMainActivity.this);
                            dao.delectAll();
                            dao.close();
	  	                	FileNameUtil fi=new FileNameUtil(OtherequipmentMainActivity.this);
	  	                	fi.delectFile("EquipementImage");
	  	                	fi.delectFile("CheckEquipementImage");
	  	                	 ProgressDialog pd=new ProgressDialog(OtherequipmentMainActivity.this);
	  	         		  
	  	       			download d=new download(pd);
	  	       			d.execute(RequestUrl.EQUIPEMENTDOWNLOAD);
	  	                	  					
	  					}
	  				});
	                     builder1.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {
	  					
	  					@Override
	  					public void onClick(DialogInterface dialog, int which) {
	  						
	  						
	  					}
	  				});
	                     //创建一个单选按钮对话框
	     	            dialog=builder1.create();
	     	            break;
	  	        }
	  	        return dialog;
	  	}
	     
      
}
